package cc.sunni.easyexcel.controller;

import cc.sunni.easyexcel.dao.DemoDAO;
import cc.sunni.easyexcel.entity.DemoData;
import cc.sunni.easyexcel.listener.DemoExcelImportListener;
import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author jiangli
 * @since 2021/3/18 14:54
 */
@RestController
@RequestMapping("/hello")
@Slf4j
public class TestController {
    @Autowired
    private DemoDAO demoDAO;

    @GetMapping
    public String hello() {
        return "hello world";
    }

    /**
     * excel导入
     */
    @PostMapping("/importExcel")
    public void importEmpBase(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        try {
            DemoExcelImportListener demoExcelImportListener = new DemoExcelImportListener(demoDAO);
            EasyExcel.read(file.getInputStream(), DemoData.class, demoExcelImportListener).sheet().doRead();
            //导出错误文件
            if (CollectionUtils.isNotEmpty(demoExcelImportListener.getErrorList())) {
                String filename = "错误信息";
                String userAgent = request.getHeader("User-Agent");
                if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                    filename = URLEncoder.encode(filename, "UTF-8");
                } else {
                    filename = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
                }
                response.setContentType("application/vnd.ms-excel");
                response.setCharacterEncoding("utf-8");
                response.addHeader("Content-Disposition", "filename=" + filename + ".xlsx");
                EasyExcel.write(response.getOutputStream(), DemoData.class).sheet("错误数据").doWrite(demoExcelImportListener.getErrorList());
            }
        } catch (IOException e) {
            log.error("导入excel失败:{}", e.getMessage(), e);
        }

    }
}
